<template>
	<eui-page-frame topHeight="260">
		<template #top>
			<view class="content-img">
				<eui-navbar ref="EuiNavBar" title="退配收货" color="#000000" backgroundColor="#FFFFFF"
					:storeName="sUserStoreName" :storeId="sUserStore" @onClickStore="clickStore">
				</eui-navbar>
				<view class="top-view">
					<eui-search-bar ref="RdsSearchBar" v-model="searchText" placeholder="请输入退配单号、商品条码、编码"
						leftIcon="icon-saoyisao" @confirm="searchConfirm" @leftIconClick="scanCode" radius="30"
						showFilter="true">
						<template v-slot:searchFields>
							<view class="search-fields">
								<view class="center">
									<eui-card-input class="search-field" v-model="formData.c_mk_dt_s" title="开始日期"
										placeholder="请选择开始日期" type="date" :displayable="false" rightIconType="clear" @iconClick="clear" singleTag="c_mk_dt_s"/>
									<eui-card-input class="search-field" v-model="formData.c_mk_dt_e" title="结束日期"
										placeholder="请选择结束日期" type="date" :displayable="false" rightIconType="clear" @iconClick="clear" singleTag="c_mk_dt_e"/>
									<eui-card-input class="search-field" v-model="formData.c_status" title="单据状态"
										type="multi" :range="statusList" />
									<eui-card-input class="search-field" v-model="formData.c_mk_username" title="制单人"
										placeholder="请选择制单人" type="text" name="rdsUsers" rightIconType="right"
										@iconClick="clickRight('user')" :displayable="true" />

								</view>
								<view class="bottom flex-1 flex">
									<eui-button type="max2" title="重置" 
										@buttonClick="confirm('reset')"></eui-button>
									<eui-button type="max" title="确认" 
										@buttonClick="confirm('fix')"></eui-button>
								</view>
							</view>
						</template>
					</eui-search-bar>
				</view>
			</view>
		</template>
		<!-- <eui-page-content> -->
			<view class="footer-view">
				<eui-virtual-list @onRefresh="getData" @lower="templateLower" refresher="true" isBottom="true"
					@itemClick="listItemClick" :origList="dataList" :options="dataOptions"  type="list">
					<template v-slot:bottom="scope">
					        <view>
					            <eui-button :modelValue="scope" type="min" title="审核" 
								:disabled="!['0'].includes(scope.c_status) || scope.c_in_store_id != sUserStore || scope.c_summary == '0'"
								@buttonClick="auditClick" />
					        </view>
					    </template>
				</eui-virtual-list>
			</view>
		<!-- </eui-page-content> -->
	</eui-page-frame>
</template>


<script setup type="ts">
	import { ref, reactive, onMounted } from 'vue';
	import {useMainStore} from "@/store/modules/store";
	import {useLoginStore} from "@/store/modules/useLoginStore";
	import { validateStores } from '@/hooks/useValidateMethod';
	import dateRangUtil from '../../../common/dateRangUtil';
	import { getRelatedName, getDictName,getDictSelectList, getDictSelect,getDictList } from '../components/RelatedName.js';
	import Enjoy from "@/common/enjoy";
	import {onLoad} from "@dcloudio/uni-app";
	import { init } from '@/hooks/init';
	import useService from '@/hooks/useService';
	import dayjs from 'dayjs';
	const service = useService({ prefix: "scApi" });
	
	const mainStore = useMainStore();
	const LoginStore = useLoginStore();
	const { loginInfo } = mainStore;
	const EuiNavBar = ref(null);
	const RdsSearchBar = ref(null);
	const sUserStore = ref(''); // 用户默认机构编码
	const sUserStoreName = ref(''); // 用户默认机构名称
	const sUser = ref(''); // 当前用户编码
	//
	const dataList = ref([]);
	const CurrentPage = ref(1); //第几页
	const PageSize = ref(10); //每页10条
	const RowsCount = ref(0); //总条数
	const PageCount = ref(1); //总页数
	const current = ref(0);
	//
	const searchText = ref('');
	const extendNavBarMenus = ref([]);
	//
	const displayable = ref(false);// true允许页面编辑
	// 查询表单
	const formData = ref({
		c_mk_dt_s: (dateRangUtil.getCurrentSeason())[0],
		c_mk_dt_e: (dateRangUtil.getCurrentSeason())[2],
		c_mk_userno: '',
		c_mk_username:'',
		c_status: '', // 0 未审核
	});
	const height = ref(0);
	/* */
	// 系统参数，字典
	const sysConfig = ref({
		c_summary: {}, // 完成情况总结： 0-未收货、1-收货中、2-部分完成、3-圆满完成
		c_status: {}, // IO类单据状态：0-尚未审核、2、预审核、3-已审核、7-已终止、8-已完成、9-已作废
	});
	const statusList = ref([]); // 查询条件状态下拉框
	const dataOptions = ref([
		{ label:"发货机构", name:"c_out_store_name",occupy: true },
		{ label: "发货品种数", name: "c_sku_out" },
		{ label: "发货部门", name: "c_out_adno_name" },
		{ label: "发货总数量", name: "c_n_out" },
		{ label: "发货仓库", name: "c_out_wno_name" },
		{ label: "发货结算总额", name: "c_at_pay_out" },
	])
	
	onLoad(async () => {
	  await init();
	  await getSysConfig();
	  if (!loginInfo.sUserStore) {
	    EuiNavBar.value.onClickStore();
	    return;
	  }
	  setDefault();
	  await getData();
	})
	const clear = (e)=>{
		switch (e) {
			case 'c_mk_dt_s':
			  formData.value.c_mk_dt_s = '';
			  break;
			case 'c_mk_dt_e':
			  formData.value.c_mk_dt_e = '';
			  break;
		}
	}
	// 点击扫描图标跳转打开摄像头
	const scanCode = () => {
	  uni.scanCode({
	    success: function (res) {
	      if (res.result != '' && res.result != undefined && res.result != null) {
	        searchText.value = res.result;
	         getData();
	      }
	    },
	  });
	}
	const getSysConfig = async() => {
		const orderList = await getDictList("订单完成情况总结");
		const ioSatusList = await getDictList("IO类单据状态");
		orderList.forEach(item => sysConfig.value.c_summary[item.c_id] = item.c_name);
		ioSatusList.forEach(e => {
			sysConfig.value.c_status[e.c_id] = e.c_name;
			statusList.value.push({
				text: e.c_name,
				value: e.c_id,
				checked: formData.value.c_status.includes(e.c_id)
			});
		});
	}
	const setDefault = () => {
		sUserStore.value = loginInfo.sUserStore;
		sUserStoreName.value = loginInfo.sUserStoreName;
		sUser.value = loginInfo.sUser;
	}
	const customId = (c_id, c_mk_dt) => {
	    return `${dayjs(c_mk_dt).format('MM/DD')} ${c_id}`;
	}
	const clickRight = (selectType) =>{
		uni.navigateTo({
		    url: `../modals/index?type=${selectType}`
		});
	}
	const SelectionChanged = (type, item) => {
		switch (type) {
			case 'user':
				formData.value.c_mk_userno = item.value;
				formData.value.c_mk_username = item.text;
				break;
		}
	}
	// 筛选条件确认
	const confirm = async(t) => {
		switch (t) {
			case 'reset':
				formData.value.c_mk_dt_s = (dateRangUtil.getCurrentSeason())[0];
				formData.value.c_mk_dt_e = (dateRangUtil.getCurrentSeason())[2];
				formData.value.c_mk_userno = '';
				formData.value.c_status = ''; // 0 未审核
				statusList.value.forEach(item => item.value == '' ? item.checked = true : item.checked = false)
				break;
			case 'fix':
				await getData();
				// 关闭弹出层
				RdsSearchBar.value.closeDrawer();
				break;
		}
    }
	// 上拉加载更多
	const templateLower = async() =>{
		if (CurrentPage.value < PageCount.value) {
			CurrentPage.value = CurrentPage.value + 1;
			await getData(true);
		}
	}
	const searchConfirm = async (e) => {
	  if (!e) {
	    return;
	  }
	  searchText.value = e.value;
	  await getData();
	}
	// 加载列表数据
	const getData = async(e) => {
		if (!e) {
			CurrentPage.value = 1;
		}
		const objectData = {
			IsNotPage: false,
			CurrentPage: CurrentPage.value,
			PageSize: PageSize.value,
			UserNo: sUser.value,
			WhereList: [
				{
					c_col: 'c_in_store_id', // 收货机构（配送中心）
					c_oper: '等于',
					c_value:sUserStore.value,
					c_logic: '而且',
				},
				{
					c_col: 'c_mk_dt',
					c_oper: '大于等于',
					c_value: formData.value.c_mk_dt_s,
					c_col_dtype: 'System.DateTime',
					c_logic: '而且',
				},
				{
					c_col: 'c_mk_dt',
					c_oper: '小于等于',
					c_value: formData.value.c_mk_dt_e,
					c_col_dtype: 'System.DateTime',
					c_logic: '而且',
				},
				{
					c_col: 'c_status',
					c_oper: '包含',
					c_value: formData.value.c_status,
					c_logic: '而且',
				},
				{
					c_col: 'c_mk_userno',
					c_col_dtype: 'System.String',
					c_left: '',
					c_oper: '=',
					c_logic: '而且',
					c_right: '',
					c_value: formData.value.c_mk_userno,
					c_group: '高级',
				},
			],
		};
		if (searchText.value) {
			// 如果 this.searchText 内容为纯数字
			if (/^\d+$/.test(searchText.value)) {
				objectData.WhereList.push({
					c_col: "c_gcode",
					c_oper: "等于",
					c_value: searchText.value, // "2000000013596",
					c_logic: "而且",
				});
			} else {
				objectData.WhereList.push({
					c_col: 'c_id',
					c_oper: '等于',
					c_value: searchText.value,
					c_logic: '而且',
				})
			}
		}
		uni.showLoading({ title: "正在加载...", mask: true })
		const result = await service.request('商品配送单', 'EnjoyQueryList', objectData,'811');
		uni.hideLoading();
		CurrentPage.value = result.CurrentPage; //第几页
		PageSize.value = result.PageSize; //每页10条
		RowsCount.value = result.RowsCount; //总条数
		PageCount.value = result.PageCount; //总页数
		const _data = result.ReturnObject.map(x=>{
			return {
				...x,
				c_out_store_name:`[${x.c_out_store_id}]${getRelatedName('rdsStores', x.c_out_store_id)||''}`,
				c_out_adno_name:`[${x.c_out_adno}]${getRelatedName('rdsDeparts', x.c_out_adno)||''}`,
				c_out_wno_name:`[${x.c_out_wno}]${getRelatedName('rdsWnos', x.c_out_wno)||''}`,
			} 
		})
		console.log("_data_data",_data)
		if (result.CurrentPage == 1) {
			dataList.value = _data;
		} else {
			dataList.value = dataList.value.concat(_data);
		}
		// 如果商品扫描出的盘单列表只有一条记录时，直接调整到盘点详情页面
		if (searchText.value && result.ReturnObject.length == 1) {
			listItemClick(result.ReturnObject[0], searchText.value);
		}
	}
    const listItemClick = (e, c_gcode = '') => {
		uni.navigateTo({
			url: './detail?id=' + e.item.c_id + '&c_gcode=' + c_gcode + '&c_store_id=' + sUserStore.value,
		});
	}
	// 选择框点击事件
	const clickStore = () => {
	  let parms = Enjoy.GetDialogParms();
	  parms.CallBack = SelectionStoreChanged;
	  parms.SelectionType = "机构选择";
	  parms.SelectedItems = sUserStore.value;
	  Enjoy.OpenDialog(parms)
	}
	const SelectionStoreChanged = async (event) => {
	  if (event.SelectionType == '机构选择') {
	    // 更新机构信息
	    sUserStoreName.value = event.BackParms.Value;
	    sUserStore.value = event.BackParms.Key;
	  }
	  // 按新条件获取数据
	  await getData();
	}
	const auditClick = async(e)=>{
		const BillId = e.modelValue.c_id;
		const objectData = {
                        BillId: BillId,
                        UserNo: sUser.value,
                    };
		  uni.showModal({
		    title: '提示',
		    content: `请确认，审核单据[${BillId}]吗?`,
		    success: async function (res) {
		      if (res.confirm) {
		        uni.showLoading({ title: "正在加载...", mask: true })
				const result = await service.request('商品配送单', 'EnjoyBillAudit', objectData,'811');
				uni.hideLoading(); 
				uni.showToast({
		          duration: 3500,
		          icon: 'none',
		          title: `审核成功！`,
		        });
		        await getData();
		      } else if (res.cancel) {
		      }
		    },
		  })
	}
	defineExpose({
		SelectionChanged
	})
</script>

<style lang="scss" scoped>
	@import '../../../main.scss';
	.content {
		display: flex;
		flex: 1;
		flex-direction: column;
		background-color: #F2F2F2;
		padding: 0px !important
	}

	.content-img {
		background-color: #FFFFFF;
		background-size: 100% 176rpx;
		background-repeat: no-repeat;
		width: 100%;
	}

	.navigation {
		flex: 0 0 auto;
		margin-bottom: 5px;
	}
	.top-view {
		width: 100%;
		height: 88rpx;
		background: #FFFFFF;
	}

	.main-view {
		flex: 1;
		flex-direction: column;
	}

	.search-fields {
		width: 100%;
		background: #FFFFFF;
		position: relative;

		.bottom {
			background: #ffffff;
			border-top: 1rpx solid $uni-line-color;
			display: flex;
			justify-content: center;
			padding: 20rpx;
		}
	}
	.status-view{
		width: 100%;
		text-align: right;
		display: flex;
		justify-content: flex-end;
		align-items: center;
	}
	.footer-view{
		height:100%;
		background: $uni-bg-color;
	}
	::v-deep .white-main{
		left:0;
		right:0;
	}
</style>